﻿using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Interface.Models;
using CNKI.TPI.Web.Search.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace CNKI.TPI.Web.Interface.Filters
{
    public class CustWepApiLoginAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext httpContext)
        {
            bool result = false;
            try
            {
                if (HttpContext.Current.Request.Path.Contains("Login")
                    || HttpContext.Current.Request.Path.Contains("Delete")
                    || HttpContext.Current.Request.Path.Contains("Insert")
                    || HttpContext.Current.Request.Path.Contains("Update")
                    || HttpContext.Current.Request.Path.Contains("GetUserRecommend")
                    || HttpContext.Current.Request.Path.Contains("Execute")
                    || HttpContext.Current.Request.Path.Contains("GetSmartword"))
                {
                    result = true;
                }
                else
                {
                    object SessionID = HttpContext.Current.Request.Cookies["tpisessionId"];
                    if (SessionID != null)
                    {
                        LoginUserInfo userInfo = SessionManager.GetUserInfo(((HttpCookie)SessionID).Value);
                        if (userInfo != null)
                        {
                            HttpContext.Current.Session.Clear();
                            HttpContext.Current.Session.Add("UserInfo", userInfo);
                            result = true;
                        }
                    }
                    else if (!ConfigHelper.IsWebApiLoginControlEnabled())
                    {
                        result = true;
                    }
                }
                HttpContext.Current.Session.Add("IP", GetIP(httpContext));
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        private string GetIP(HttpActionContext httpContext)
        {
            HttpContextBase context = (HttpContextBase)httpContext.Request.Properties["MS_HttpContext"];//获取传统context
            return IPUntil.GetIP(context.Request);
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            OutputEntity oe = new OutputEntity();
            oe.Status = Status.InvalidSessionID;
            actionContext.Response = actionContext.Request.CreateResponse();
            actionContext.Response.Content = new StringContent(SerializeHelper.Serialize(oe));
        }
    }
}